<template>
  <div>
    <el-drawer
      :title="operation === 'add' ? '新增切换支付渠道' : '编辑切换支付渠道'"
      :visible="channelDialog"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
      :before-close="handleClose"
      size="70%"
    >
      <div class="demo-drawer__content">
        <el-radio-group
          v-model="baseInfo.wayPayWay"
          style="margin-bottom: 10px"
        >
          <el-radio :label="0">按时间设置</el-radio>
          <el-radio :label="1">按订单笔数</el-radio>
          <el-radio :label="2">按油枪设置</el-radio>
        </el-radio-group>

        <div>
          <el-row v-show="listOptions.length === 0">
            未查到相关数据，尝试关闭刷新后操作
          </el-row>
          <el-row v-for="(optionsItem, index) in listOptions" :key="index">
            <el-col :span="18" style="border: 1px solid #ddd; padding: 10px">
              <!-- 时间选择-- 按时间设置 -->
              <el-row
                v-show="baseInfo.wayPayWay === 0"
                style="margin-bottom: 20px"
              >
                <el-col :span="24" style="font-size: 14px">选择时间</el-col>
                <el-col :span="24">
                  <el-checkbox-group v-model="optionsItem.weeks" size="mini">
                    <el-checkbox-button
                      v-for="(item, i) in weeksList"
                      :label="i + 1"
                      :key="i + 1"
                    >
                      {{ item }}
                    </el-checkbox-button>
                  </el-checkbox-group>
                </el-col>
                <el-col>
                  <el-time-select
                    placeholder="起始时间"
                    value-format="HH"
                    v-model="optionsItem.beginTime"
                    size="small"
                    :picker-options="{
                      start: '00:00',
                      step: '01:00',
                      end: '23:00',
                      maxTime: optionsItem.endTime,
                    }"
                  >
                  </el-time-select>
                  <el-time-select
                    placeholder="结束时间"
                    v-model="optionsItem.endTime"
                    size="small"
                    :picker-options="{
                      start: '00:00',
                      step: '01:00',
                      end: '24:00',
                      minTime: optionsItem.beginTime,
                    }"
                  >
                  </el-time-select>
                </el-col>
              </el-row>

              <!-- 订单笔数输入框--- 按订单笔数 -->
              <el-row
                v-show="baseInfo.wayPayWay === 1"
                style="margin-bottom: 20px"
              >
                <el-col style="font-size: 14px">订单笔数</el-col>
                <el-col>
                  <el-input
                    placeholder="请输入订单笔数"
                    v-model="optionsItem.orderCount"
                    type="number"
                    size="small"
                    @change="validateOrderCount"
                  ></el-input>
                </el-col>
              </el-row>
              <!-- 选择油企 -->
              <el-row style="margin-bottom: 20px">
                <el-col :span="24" style="font-size: 14px">
                  {{ index === 0 ? "选择油企" : "选择油站" }}
                </el-col>
                <el-col :span="24">
                  <el-select
                    style="width: 180px"
                    v-model="baseInfo.enterpriseId"
                    :clearable="true"
                    filterable
                    placeholder="请选择油企"
                    size="small"
                    @change="handleSelectChange"
                    v-show="index === 0"
                    :disabled="operation === 'edit'"
                  >
                    <el-option
                      v-for="(item, i2) in enterpriseList"
                      :key="i2"
                      :value="item.enterpriseId"
                      :label="item.enterpriseName"
                    ></el-option>
                  </el-select>
                  <el-select
                    style="width: 180px"
                    v-model="optionsItem.stationId"
                    :clearable="true"
                    filterable
                    size="small"
                    placeholder="请选择油站名称"
                    @change="handleSelectStation(index, optionsItem.stationId)"
                  >
                    <el-option
                      v-for="item in stationList"
                      :key="item.stationId"
                      :label="item.stationName"
                      :value="item.stationId"
                    >
                    </el-option>
                  </el-select>
                </el-col>
              </el-row>

              <!-- 油枪---按油枪设置 -->
              <el-row
                v-show="baseInfo.wayPayWay === 2"
                style="margin-bottom: 20px"
              >
                <el-col style="font-size: 14px">油枪</el-col>
                <el-col
                  v-show="
                    optionsItem &&
                    optionsItem.gunList &&
                    optionsItem.gunList.length === 0
                  "
                  style="color: #999"
                >
                  空空如也
                </el-col>
                <el-col
                  v-show="
                    optionsItem &&
                    optionsItem.gunList &&
                    optionsItem.gunList.length > 0
                  "
                >
                  <el-checkbox-group v-model="optionsItem.oilGun" size="mini">
                    <el-checkbox-button
                      v-for="(item, index) in optionsItem.gunList"
                      :label="item"
                      :key="index"
                    >
                      {{ item }}号枪
                    </el-checkbox-button>
                  </el-checkbox-group>

                  <!-- <el-radio-group v-model="optionsItem.oilGun" size="small">
                    <el-radio-button
                      v-for="(item, index) in optionsItem.gunList"
                      :label="item"
                      :key="index"
                      >{{ item }}号枪</el-radio-button
                    >
                  </el-radio-group> -->
                </el-col>
              </el-row>
              <!-- 选择支付渠道： 这里仅作展示 -->
              <el-row style="margin-bottom: 20px">
                <el-col :span="24" style="font-size: 14px">选择支付渠道</el-col>
                <el-col :span="24">
                  <el-button
                    @click="handlePayWayOpen(optionsItem, index)"
                    size="small"
                    type="primary"
                  >
                    选择
                  </el-button>
                </el-col>

                <el-col :span="24">
                  <el-checkbox-group
                    v-model="optionsItem.payWayIdList"
                    size="mini"
                  >
                    <el-checkbox
                      v-for="(item, index) in currentPayWayList"
                      :key="index"
                      :label="item.payWayId"
                      disabled
                    >
                      {{ item.payWayId }}
                      -
                      {{
                        item.appType == "1"
                          ? "微信"
                          : "" + item.appType == "2"
                          ? "支付宝"
                          : "" + item.appType == "3"
                          ? "银行卡"
                          : "" + item.appType == "4"
                          ? "POS机"
                          : ""
                      }}
                      -
                      {{
                        item.useType == "1"
                          ? "消费"
                          : "" + item.useType == "0"
                          ? "充值"
                          : ""
                      }}
                      -
                      {{
                        item.payType == "1"
                          ? "随行付"
                          : "" + item.payType == "2"
                          ? "云闪付"
                          : "" + item.payType == "3"
                          ? "通联支付"
                          : "" + item.payType == "4"
                          ? "金控"
                          : "" + item.payType == "5"
                          ? "云化支付"
                          : ""
                      }}-{{ item.remark }}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-col>
                <el-col>
                  <div style="font-size: 12px; color: gray; text-align: center">
                    {{
                      currentPayWayList.length
                        ? " 同一支付方式、消费方式只能选择一种支付渠道"
                        : "没有查到支付渠道"
                    }}
                  </div>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="6">
              <el-button
                type="primary"
                size="small"
                @click="handlAddItem(index)"
              >
                添加
              </el-button>
              <el-button
                size="small"
                @click="handleDelete1(index)"
                v-show="listOptions.length > 1"
              >
                删除
              </el-button>
            </el-col>
          </el-row>
        </div>

        <!-- 提交 -->
        <div class="demo-drawer__footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button
            type="primary"
            @click="submitForm"
            :disabled="isNoToSubmit"
          >
            确 定
          </el-button>
        </div>

        <!-- 选择支付渠道弹框 -->
        <el-dialog
          :title="'选择支付渠道'"
          :visible.sync="payWayOpen"
          width="800px"
          append-to-body
          :close-on-click-modal="false"
        >
          <el-form
            ref="payWayForm"
            :model="payWayForm"
            :rules="payWayRules"
            label-width="80px"
            label-position="top"
          >
            <el-col :span="23">
              <el-form-item label="" prop="payWayIdList">
                <el-checkbox-group
                  v-model="payWayForm.payWayIdList"
                  size="mini"
                >
                  <el-checkbox
                    v-for="(item, index) in currentPayWayList"
                    :key="index + 1"
                    :label="item.payWayId"
                  >
                    {{ item.payWayId }}
                    -
                    {{
                      item.appType == "1"
                        ? "微信"
                        : "" + item.appType == "2"
                        ? "支付宝"
                        : "" + item.appType == "3"
                        ? "银行卡"
                        : "" + item.appType == "4"
                        ? "POS机"
                        : ""
                    }}
                    -
                    {{
                      item.useType == "1"
                        ? "消费"
                        : "" + item.useType == "0"
                        ? "充值"
                        : ""
                    }}
                    -
                    {{
                      item.payType == "1"
                        ? "随行付"
                        : "" + item.payType == "2"
                        ? "云闪付"
                        : "" + item.payType == "3"
                        ? "通联支付"
                        : "" + item.payType == "4"
                        ? "金控"
                        : "" + item.payType == "5"
                        ? "云化支付"
                        : ""
                    }}-{{ item.remark }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
            <el-col :span="23">
              <div style="font-size: 12px; color: gray; text-align: center">
                同一支付方式、消费方式只能选择一种支付渠道
              </div>
            </el-col>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" size="mini" @click="payWaySubmitForm">
              确 定
            </el-button>
            <el-button size="mini" @click="payWayCancel">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import {
  getStationList,
  listEnterpriseStation,
  getPayWayList,
  getOilAndGunList,
} from "@/api/dept";

import { addPayWayApi, getPayWayInfoApi, editPayWayApi } from "@/api/payway";
import { enterpriseList } from "@/api/station/orderHistory";
import { cloneDeep } from "lodash";

export default {
  name: "AddOrEditChannel",
  props: {
    channelDialog: {
      type: Boolean,
      default: false,
    },
    operation: {
      type: String,
      default: "add",
    },
    currentRow: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    // 校验支付渠道勾选--同一支付方式、消费方式只能选择一种支付渠道
    let validatePayWayIdList = (rule, value, callback) => {
      let compareArr = [];
      this.payWayForm.payWayIdList.map((id) => {
        const payWay = this.currentPayWayList.find((ele) => ele.payWayId == id);
        if (!!payWay) {
          let str = payWay.appType + payWay.useType;
          compareArr.push(str);
        }
      });
      const length1 = compareArr.length;
      const length2 = new Set(compareArr).size;
      if (length1 != length2) {
        callback(
          new Error(
            "同一支付方式、消费方式只能选择一种支付渠道，请检查选项的冲突"
          )
        );
      }
      callback();
      return;
    };
    return {
      drawer: true,
      form: {},
      formLabelWidth: "80px",
      enterpriseList: [],
      stationList: [],
      loading: false,
      // 空对象模板
      emptyInfo: {
        enterpriseId: null,
        wayPayWay: 0, // 0按时间设置  1按订单笔数  2 按油枪设置
        weeks: [], // 星期
        payWayIdList: [], // 支付渠道列表
        beginTime: null,
        endTime: null,
        orderCount: null, // 订单笔数
        oilGun: [], // 油枪号
      },
      // 基本对象数据
      baseInfo: {
        wayPayWay: 0, // 0按时间设置  1按订单笔数  2 按油枪设置
        enterpriseId: null,
        weeks: [],
        beginTime: null,
        endTime: null,
        orderCount: null, // 订单笔数
        oilGun: [], // 油枪号
      },
      // 列表配置项
      listOptions: [
        {
          stationId: null,
          wayPayWay: 0,
          weeks: [],
          beginTime: null,
          endTime: null,
          payWayIdList: [], // 支付渠道列表id集合
          gunList: [],
          oilGun: [],
        },
      ],

      payWayForm: {
        payWayIdList: [],
      },
      // 按时间设置的表单校验规则
      payWayRules: {
        payWayIdList: [
          { required: true, message: "请选择支付渠道", trigger: "change" },
          { validator: validatePayWayIdList, trigger: "change" },
        ],
      },
      weeksList: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
      currentPayWayList: [], // 当前选中的支付渠道
      currentPayWayList: [],
      gunList: ["1", "2", "3"], // 油枪列表
      payWayOpen: false,
      currentPaySelectIndex: 0, // 当前编辑的表单的索引
      isNoToSubmit: false, // 控制是否可以点击提交按钮
    };
  },

  watch: {
    // 监听弹框
    channelDialog(val) {
      if (val) {
        // 重置基本表单项
        this.baseInfo = this.currentRow;
        // 重置表单配置列表
        this.listOptions = [
          {
            stationId: null,
            wayPayWay: 0,
            weeks: [],
            beginTime: null,
            endTime: null,
            payWayIdList: [], // 支付渠道列表id集合
            gunList: [], // 用于保存当前项的油枪列表
            oilGun: [],
          },
        ];
        // 重置支付渠道
        this.currentPayWayList = [];
        this.getEnterpriseList(); // 获取油企列表
        if (this.currentRow.id) {
          // 获取相关数据回显
          this.getPayWayList(this.currentRow.enterpriseId); // 获取当前油企的支付渠道
          this.getPayWayInfo(); // 获取支付渠道详情
          this.getStationList(this.currentRow.enterpriseId); // 获取油站列表
          this.baseInfo.enterpriseId = this.currentRow.enterpriseId; // 油企回显
        }
      }
    },

    // 监听设置方式的变化: 值发生变化就把之前的重置清空
    "baseInfo.wayPayWay": {
      handler(newVal, oldVal) {
        let obj = { ...this.emptyInfo };
        let item = {
          stationId: null,
          wayPayWay: 0,
          weeks: [],
          beginTime: null,
          endTime: null,
          payWayIdList: [],
          gunList: [],
          oilGun: [],
        };
        if (this.operation === "add") {
          if (newVal === 0) {
            // 按时间设置
            obj.wayPayWay = 0;
            item.wayPayWay = 0;
          }
          if (newVal === 1) {
            // 按订单设置
            obj.wayPayWay = 1;
            item.wayPayWay = 1;
          }
          if (newVal === 2) {
            // 按油枪设置
            obj.wayPayWay = 2;
            item.wayPayWay = 2;
          }
          this.baseInfo = obj;
          this.listOptions = [item];
        }
      },
    },
  },
  methods: {
    // 选择支付渠道弹框-确认
    payWaySubmitForm: function () {
      this.$refs["payWayForm"].validate((valid) => {
        if (valid) {
          let index = this.currentPaySelectIndex;
          this.listOptions[index].payWayIdList = this.payWayForm.payWayIdList;
          this.payWayOpen = false;
          // this.payWayForm.payWayIdList = []; // 表单清空
        }
      });
    },
    // 选择支付渠道弹框--打开
    handlePayWayOpen(item, index) {
      this.currentPaySelectIndex = index;
      this.currentPayWayList = this.currentPayWayList;

      // 不管当前时add还是edit，不管有没有数据，直接把外边的值回显到弹框里面
      this.payWayForm.payWayIdList = this.listOptions[index].payWayIdList;
      this.payWayOpen = true;
    },
    // 选择支付渠道弹框关闭
    payWayCancel() {
      this.payWayForm.payWayIdList = []; // 清空已选择的内容
      this.payWayOpen = false;
    },

    // 1、关闭抽屉
    handleClose(done) {
      const _this = this;
      this.$confirm("确认关闭？")
        .then((_) => {
          _this.$emit("update:channelDialog", false);
        })
        .catch((_) => {});
    },
    // 2、查询油企列表
    getEnterpriseList() {
      enterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },
    //3、 选择油企
    handleSelectChange(enterpriseId) {
      this.stationList = [];
      // 清空所有表单的油站
      this.listOptions.forEach((item) => {
        item.stationId = null;
      });
      this.getStationList(enterpriseId);
      if (enterpriseId) {
        this.getPayWayList(enterpriseId); //  获取支付渠道列表
      } else {
        this.currentPayWayList = [];
      }
    },

    // 4、选择油站时
    handleSelectStation(formIndex, stationId) {
      // formIndex  :当前编辑的表单对应的索引：
      this.getGunList(formIndex, stationId);
    },

    //5、 获取油站
    async getStationList(enterpriseId) {
      const res = await listEnterpriseStation({ enterpriseId: enterpriseId });
      this.stationList = res;
    },

    //6、 获取当前油企下的支付渠道列表
    async getPayWayList(id) {
      const res = await getPayWayList({
        enterpriseId: id,
        pageSize: 10000,
        pageNum: 1,
      });
      this.currentPayWayList = res.rows;
      console.log("渠道列表", this.currentPayWayList);
    },

    // 7、获取油站的油枪
    async getGunList(formIndex, stationId) {
      const res = await getOilAndGunList({ stationId });
      let list = res.rows;
      let arr = [];
      list.forEach((item) => {
        arr = [...arr, ...item.gunNameList];
      });
      arr = arr.map(Number); // 转化数字
      // 升序
      arr.sort((a, b) => {
        return a - b;
      });
      console.log("油枪列表", arr);
      this.$set(this.listOptions[formIndex], "gunList", arr);
      return arr;
    },

    // 9、添加 一个列表项
    handlAddItem(index, action = "add") {
      let isOk = this.validatePayWayList("add");
      const item = {
        stationId: null,
        wayPayWay: 0, // 0按时间设置  1按订单笔数  2 按油枪设置
        weeks: [],
        payWayIdList: [], // 支付渠道列表
        beginTime: null,
        endTime: null,
        gunList: [],
        oilGun: [],
      };
      if (isOk) {
        this.listOptions.push(item);
      }
    },

    //10、 删除一个表单列表项
    handleDelete1(index) {
      this.listOptions.splice(index, 1);
    },

    // 11、根据渠道id获取支付渠道详情,进行数据回显
    async getPayWayInfo() {
      let id = this.currentRow.id;
      const res = await getPayWayInfoApi({ id: id });
      let list = [...res];
      list.forEach(async (item, index) => {
        // 星期的数据回显
        if (item.weeks && item.weeks.length) {
          item.weeks = item.weeks.split(",").map((week) => Number(week));
        } else {
          item.weeks = [];
        }
        // 支付渠道的数据回显
        item.payWayIdList = item.payWayIdList
          .split(",")
          .map((pay) => Number(pay));

        // 油枪数据的回显
        if (item.oilGun && item.oilGun.length) {
          item.oilGun = item.oilGun.split(",").map((item) => Number(item));
        }
        // 油枪列表：获取每一个选择的油站的油枪列表
        item.gunList = await this.getGunList(index, item.stationId);
      });
      this.listOptions = list;
    },

    // 校验订单笔数
    validateOrderCount(count) {
      if (count.length > 11) {
        this.isNoToSubmit = true;
        return this.msgError("最大长度11位");
      }

      let orderCount = Number(count);
      const pattern = /^\d+(\.\d{0,0})?$/; // 整数

      if (Number.isNaN(orderCount)) {
        this.isNoToSubmit = true;
        return this.msgError("请输入有效数值");
      }
      if (orderCount < 0) {
        this.isNoToSubmit = true;
        return this.msgError("不能小于等于0");
      }
      if (orderCount == 0) {
        this.isNoToSubmit = true;
        return this.msgError("请输入有效值");
      }
      if (!pattern.test(orderCount)) {
        this.isNoToSubmit = true;
        return this.msgError("请输入整数");
      }
      this.isNoToSubmit = false;
    },

    // 校验每一个表单项
    validatePayWayList(action) {
      let wayPayWay = this.baseInfo.wayPayWay;
      let baseInfo = this.baseInfo;
      let listOptions = this.listOptions;
      let isOk = true;

      if (action === "add" && listOptions.length >= 4) {
        this.msgError("最多只能添加四个");
        isOk = false;
        return;
      }

      if (!baseInfo.enterpriseId) {
        this.msgError("请选择油企");
        isOk = false;
        return;
      }

      listOptions.forEach((obj) => {
        if (!obj.stationId) {
          this.msgError("请选择油站");
          isOk = false;
          return;
        }

        if (!obj.payWayIdList.length) {
          this.msgError("请选择支付渠道");
          isOk = false;
          return;
        }

        // 选择按时间设置的校验
        if (baseInfo.wayPayWay === 0) {
          if (!obj.weeks.length) {
            this.msgError("请选择星期");
            isOk = false;
            return;
          }
          if (!obj.beginTime) {
            this.msgError("请选择开始时间");
            isOk = false;
            return;
          }
          if (!obj.endTime) {
            this.msgError("请选择结束时间");
            isOk = false;
            return;
          }
        }
        // 选择按订单笔数的校验
        if (baseInfo.wayPayWay === 1) {
          if (!obj.orderCount) {
            this.msgError("请输入订单笔数");
            isOk = false;
            return;
          }
        }
        // 选择按油枪的校验
        if (baseInfo.wayPayWay === 2) {
          if (!obj.oilGun.length) {
            this.msgError("请选择油枪");
            isOk = false;
            return;
          }
        }
      });
      return isOk;
    },

    // 12、点击提交
    submitForm(formName) {
      const _this = this;
      let isOk = this.validatePayWayList("save"); // 提交前再做一次校验
      if (isOk) {
        this.$confirm(
          "保存前请检查支付渠道是否完全勾选，如之前正常使用的渠道漏勾选设置，将影响该渠道使用",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then(async () => {
          const params = {};
          params.autoPayWayInfos = cloneDeep(_this.listOptions); // 每个设置表单的设置项, 深克隆一下，不影响原来的数据
          params.enterpriseId = _this.baseInfo.enterpriseId;
          params.wayPayWay = _this.baseInfo.wayPayWay; // 设置方式 0 1 2

          let wayPayWay = this.baseInfo.wayPayWay;

          // 统一处理一下支付方式，时间，订单，油枪等字段,拼接成字符串格式
          params.autoPayWayInfos.forEach((item) => {
            item.payWayIdList = item.payWayIdList.join(","); // 支付渠道
            item.weeks =
              wayPayWay === 0 && item.weeks.length ? item.weeks.join(",") : "";
            item.orderCount = wayPayWay === 1 ? item.orderCount : "";
            item.oilGun = wayPayWay === 2 ? item.oilGun.join(",") : "";
            item.beginTime = wayPayWay === 0 ? item.beginTime : "";
            item.endTime = wayPayWay === 0 ? item.endTime : "";
          });
          console.log("参数---", params);
          if (_this.operation === "add") {
            await addPayWayApi(params);
            _this.msgSuccess("新增成功");
          }
          if (_this.operation === "edit") {
            params.id = _this.currentRow.id;
            await editPayWayApi(params);
            _this.msgSuccess("编辑成功");
          }
          _this.$emit("update:channelDialog", false);
          _this.$emit("reloadData");
        });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .demo-drawer {
  .el-drawer__body {
    padding: 20px;
    overflow: auto;
    .demo-drawer__footer {
      text-align: end;
      margin-top: 20px;
    }

    .demo-drawer__content {
      .demo-ruleForm {
        padding: 20px 0px;
        border: 1px solid #ddd;
      }
    }
  }
}
</style>
